<script setup lang="ts">
import {
  getCurrentInstance,
  nextTick,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue'
import CommonBaseInfoTable from '@/views/project-update/month-report/common-base-info-table.vue'
import { getAreaStorageDetail } from '@/api/project-update/area-storage'
import { Message } from 'element-ui'

const vm = getCurrentInstance()

const props = defineProps({
  pkid: String,
  regionList: Array,
  userLevel: Number,
  regionId: String,
  disabled: Boolean,
})

const form = reactive({})

const projectBasePart2 = ref([
  {
    label: '片区名称',
    key: 'regionName',
    renderType: 'render',
    labelClass: 'required-label',
  },
  {
    label: '位置范围',
    key: 'locationRange',
    renderType: 'render',
    contentClass: 'no-padding-content',
    labelClass: 'required-label',
  },
  {
    label: '项目类型（可多选）',
    key: 'peType',
    renderType: 'checkbox',
    calc: true,
    options: [
      { label: '老旧小区（街区）', value: '01' },
      { label: '老旧商业区', value: '02' },
      { label: '老旧厂区', value: '03' },
      { label: '历史文化区', value: '04' },
      { label: '公共空间', value: '05' },
      { label: '其他', value: '10', input: true, otherKey: 'other1' },
    ],
    labelClass: 'required-label',
  },
])

const projectBasePart4 = ref([
  {
    label: '更新总体目标',
    key: 'updateTarget',
    renderType: 'textarea',
  },
  {
    label: '更新纬度',
    key: 'latitude',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '生活功能',
    key: 'lifeFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '生态功能',
    key: 'ecologicalFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '产业功能',
    key: 'industryFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '文化功能',
    key: 'cultureFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '安全功能',
    key: 'securityFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '交通功能',
    key: 'trafficFunction',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '其他',
    key: 'other',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
  {
    label: '片区更新指标',
    key: 'targetIndex',
    renderType: 'render',
    contentClass: 'no-padding-content project-update-index',
  },
  {
    label: '项目实施计划',
    key: 'implementationPlan',
    renderType: 'render',
    contentClass: 'no-padding-content',
  },
])

const locationRangeTableProps = ref([
  {
    label: '所属区县',
    key: 'regionName',
    renderType: 'render',
  },
  {
    label: '所属街道',
    key: 'street',
    renderType: 'render',
  },
  {
    label: '东至',
    key: 'east',
    renderType: 'input',
  },
  {
    label: '南至',
    key: 'south',
    renderType: 'input',
  },
  {
    label: '西至',
    key: 'west',
    renderType: 'input',
  },
  {
    label: '北至',
    key: 'north',
    renderType: 'input',
  },
  {
    label: '总占地面积（公顷）',
    key: 'area',
    renderType: 'input',
  },
])

const targetIndexTableProps = ref([
  {
    label: '①现状总建筑面积（m²）',
    key: 'beforeTotalArea',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '②拟保留和改造建筑面积（m²）',
    key: 'beforeReformArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '③拟拆除建筑面积（m²）',
    key: 'beforeDismantleArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '④更新后总建筑面积（m²）',
    key: 'afterTotalArea',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '⑤拟保留和改造建筑面积（m²）',
    key: 'afterReformArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '⑥改造中增加建筑面积（m²）',
    key: 'afterDismantle',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
  {
    label: '⑦新增建筑面积（m²）',
    key: 'afterBuildingArea',
    renderType: 'input',
    placeholder: '请输入',
    calc: true,
  },
])

const targetIndexTableProps2 = ref([
  {
    label: '拆除比例（%）',
    key: 'beforeRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
  {
    label: '拆建比例（%）',
    key: 'afterRatio',
    renderType: 'input',
    placeholder: '请输入',
    disabled: true,
  },
])

const tableData = ref([])

const implementationPlanTableProps = ref([
  {
    label: '序号',
    key: 'index',
    renderType: 'index',
    width: '60',
  },
  {
    label: '项目名称',
    key: 'regionName',
    renderType: 'input',
    width: '180',
  },
  {
    label: '更新内容',
    key: 'updateContent',
    renderType: 'input',
    placeholder: '请输入',
    width: '180',
  },
  {
    label: '项目实施计划',
    key: 'investment',
    renderType: 'render',
    children: [
      {
        label: '2024年',
        key: 'thisYear',
      },
      {
        label: '2025年',
        key: 'nextYear',
      },
      {
        label: '2026年',
        key: 'afterYear',
      },
    ],
  },
])

const streetId = ref('')
const streetList = ref([])

const infoRef1 = ref(null)
const infoRef2 = ref(null)
const infoRef3 = ref(null)
const infoRef4 = ref(null)
const infoRef5 = ref(null)

const getSubmitData = () => {
  const data1 = infoRef1.value.getFilledFormData()
  const data2 = infoRef2.value.getFilledFormData()
  const data3 = infoRef3.value.getFilledFormData()
  const data4 = infoRef4.value.getFilledFormData()
  const data5 = infoRef5.value.getFilledFormData()
  return {
    ...data1,
    ...data2,
    ...data3,
    ...data4,
    ...data5,
    ...form,
    peType: data1.peType.join(';'),
    projectList: tableData.value,
    district: props.regionId,
    street: streetId.value.toString(),
  }
}

watch(
  () => props.regionList,
  (val) => {
    if (val) {
      streetList.value =
        val.find((item) => item.pkid === props.regionId)?.children || []
    }
  }
)

watch(
  () => props.regionId,
  (val) => {
    streetId.value = ''
    if (val) {
      streetList.value =
        props.regionList.find((item) => item.pkid === val)?.children || []
    } else {
      streetList.value = []
    }
  }
)

const getRegionName = (id: string) => {
  return props.regionList.find((item) => item.pkid === id)?.areaName || ''
}

const getStreetName = (ids: string[]) => {
  return streetList.value
    .filter((item) => ids.includes(item.pkid))
    .map((item) => item.areaName)
    .join(',')
}

const emit = defineEmits(['changeRegionId'])

const formKeys = [
  'id',
  'regionName',
  'shgn1',
  'shgn2',
  'stgn1',
  'stgn2',
  'cygn1',
  'cygn2',
  'whgn1',
  'whgn2',
  'aqgn1',
  'aqgn2',
  'jtgn1',
  'jtgn2',
  'other2',
  'other3',
]

onBeforeMount(() => {
  formKeys.forEach((key) => {
    vm?.proxy.$set(form, key, '')
  })
})

const initData = (id) => {
  getAreaStorageDetail(id || props.pkid).then((res) => {
    if (res.success) {
      const data = res.data
      if (!data) return
      data.peType = data.peType?.split(';') || []
      infoRef1.value.inputData(data)
      infoRef2.value.inputData(data)
      infoRef3.value.inputData(data)
      infoRef4.value.inputData(data)
      infoRef5.value.inputData(data)
      formKeys.forEach((key) => {
        form[key] = data[key] ?? ''
      })
      emit('changeRegionId', data.district)
      tableData.value = data.projectList || []
      nextTick(() => {
        streetId.value = data.street?.split(',') || []
      })
    } else {
      Message.error(res.message)
    }
  })
}

onMounted(() => {
  if (!props.pkid) return
  initData()
})

const handleAddTableData = () => {
  tableData.value.push({
    regionName: '',
    updateContent: '',
    thisYear: '',
    nextYear: '',
    afterYear: '',
  })
}

const handleRemoveClick = (index: number) => {
  tableData.value.splice(index, 1)
}

const getNumber = (str: string) => {
  return Number(str) || 0
}

const handleCalcNum = (formData: any) => {
  console.log(formData)

  const beforeDismantleArea = getNumber(formData['beforeDismantleArea'])
  const beforeTotalArea =
    getNumber(formData['beforeReformArea']) + beforeDismantleArea

  const beforeRatio = beforeTotalArea
    ? beforeDismantleArea / beforeTotalArea
    : 0

  const afterTotalArea =
    getNumber(formData['afterReformArea']) +
    getNumber(formData['afterBuildingArea']) +
    getNumber(formData['afterDismantle'])

  const afterRatio = beforeDismantleArea
    ? (getNumber(formData['afterBuildingArea']) +
        getNumber(formData['afterDismantle'])) /
      beforeDismantleArea
    : 0

  infoRef4.value.inputData({
    beforeTotalArea,
    afterTotalArea,
  })
  infoRef5.value.inputData({
    beforeRatio: (beforeRatio * 100).toFixed(2),
    afterRatio: (afterRatio * 100).toFixed(2),
  })
}

defineExpose({
  initData,
  getSubmitData,
})
</script>

<template>
  <el-form class="detail-table" :disabled="disabled">
    <common-base-info-table
      ref="infoRef1"
      :base-info-table-props="projectBasePart2"
      :border="true"
      :column="1"
      class="cell-num-1"
    >
      <template #regionName>
        <el-input v-model="form.regionName" placeholder="请输入"></el-input>
      </template>
      <template #locationRange>
        <common-base-info-table
          ref="infoRef2"
          :column="7"
          :border="true"
          :base-info-table-props="locationRangeTableProps"
          :direction="'vertical'"
        >
          <template #regionName>
            <template v-if="userLevel === 0 || userLevel === 5">
              <el-select :value="regionId" placeholder="待选择" disabled>
                <el-option
                  v-for="item in regionList"
                  :key="item.pkid"
                  :label="item.areaName"
                  :value="item.pkid"
                ></el-option>
              </el-select>
            </template>
            <template v-else> {{ getRegionName(regionId) }} </template>
          </template>
          <template #street>
            <template
              v-if="userLevel === 0 || userLevel === 5 || userLevel === 2"
            >
              <el-select v-model="streetId" placeholder="请选择" multiple>
                <el-option
                  v-for="item in streetList"
                  :key="item.pkid"
                  :label="item.areaName"
                  :value="item.pkid"
                ></el-option>
              </el-select>
            </template>
            <template v-else>
              {{ getStreetName(streetId) }}
            </template>
          </template>
        </common-base-info-table>
      </template>
    </common-base-info-table>
    <common-base-info-table
      ref="infoRef3"
      :base-info-table-props="projectBasePart4"
      :border="true"
      :column="1"
      class="cell-num-1-last"
    >
      <template #latitude>
        <div class="table-inline-item">
          <div class="table-property">针对现状及问题分析诊断</div>
          <div class="table-property">主要更新措施</div>
        </div>
      </template>
      <template #lifeFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.shgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.shgn2"></el-input>
          </div>
        </div>
      </template>
      <template #ecologicalFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.stgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.stgn2"></el-input>
          </div>
        </div>
      </template>
      <template #industryFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.cygn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.cygn2"></el-input>
          </div>
        </div>
      </template>
      <template #cultureFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.whgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.whgn2"></el-input>
          </div>
        </div>
      </template>
      <template #securityFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.aqgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.aqgn2"></el-input>
          </div>
        </div>
      </template>
      <template #trafficFunction>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.jtgn1"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.jtgn2"></el-input>
          </div>
        </div>
      </template>
      <template #other>
        <div class="table-inline-item">
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.other2"></el-input>
          </div>
          <div class="table-content-item">
            <el-input placeholder="请输入" v-model="form.other3"></el-input>
          </div>
        </div>
      </template>
      <template #targetIndex>
        <div class="target-index-content">
          <div class="table-inline-item">
            <div class="table-property">现状建筑面积指标</div>
            <div class="table-property">更新后建筑面积指标</div>
          </div>
          <common-base-info-table
            ref="infoRef4"
            :column="7"
            :border="true"
            :base-info-table-props="targetIndexTableProps"
            :direction="'vertical'"
            class="cell-num-7"
            @calcNum="handleCalcNum"
          />
          <common-base-info-table
            ref="infoRef5"
            :column="2"
            :border="true"
            :base-info-table-props="targetIndexTableProps2"
            class="cell-num-2-inner"
          />
        </div>
      </template>
      <template #implementationPlan>
        <el-table :data="tableData" border>
          <template v-for="item in implementationPlanTableProps">
            <template v-if="item.renderType !== 'render'">
              <el-table-column
                :key="item.label"
                :label="item.label"
                :width="item.width"
              >
                <template #default="scope" v-if="item.renderType === 'index'">
                  {{ scope.$index + 1 }}
                </template>
                <template
                  #default="scope"
                  v-else-if="item.renderType === 'input'"
                >
                  <el-input
                    v-model="scope.row[item.key]"
                    placeholder="请输入"
                  ></el-input>
                </template>
                <template
                  #default="scope"
                  v-else-if="item.renderType === 'year'"
                >
                  <el-date-picker
                    v-model="scope.row[item.key]"
                    type="year"
                    placeholder="选择年份"
                  ></el-date-picker>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column :key="item.label" :label="item.label">
                <el-table-column
                  v-for="child in item.children"
                  :key="child.label"
                  :label="child.label"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row[child.key]"
                      placeholder="请输入"
                    ></el-input>
                  </template>
                </el-table-column>
              </el-table-column>
            </template>
          </template>
          <el-table-column label="操作" width="100">
            <template slot="header">
              <el-button type="text" @click="handleAddTableData">
                <i
                  class="el-icon-circle-plus-outline"
                  style="font-size: 16px"
                ></i>
              </el-button>
            </template>
            <template v-slot="scope">
              <el-button type="text" @click="handleRemoveClick(scope.$index)">
                <i
                  style="color: #f78989; font-size: 18px"
                  class="el-icon-delete"
                  :key="scope.$index"
                ></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </common-base-info-table>
  </el-form>
</template>

<style scoped lang="scss">
.detail-table {
  width: 100%;

  $base-cell-width: calc(100% / 8);

  .name-inline {
    display: flex;
    align-items: center;

    .el-input {
      width: 220px;
      margin-right: 12px;
    }
  }

  .cell-num-1 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }
    }
  }

  .cell-num-1-last {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 7;
      }
    }
  }

  .cell-num-2 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 3;
      }
    }
  }

  .cell-num-3 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width;
      }

      .el-descriptions-item__content:nth-child(2) {
        width: $base-cell-width * 2;
      }
    }
  }

  :deep(.no-padding-content) {
    padding: 0 !important;
  }

  .target-index-content {
    width: 100%;
  }
  .cell-num-7 {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width;
      }

      .el-descriptions-item__content {
        width: $base-cell-width;
      }
    }
  }

  .cell-num-1-inner {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width * 1.15;
      }
    }
  }

  .cell-num-2-inner {
    :deep(.el-descriptions-row) {
      .el-descriptions-item__label {
        width: $base-cell-width * 1;
      }

      .el-descriptions-item__content {
        width: $base-cell-width * 2.5;
      }
    }
  }
  .table-inline-item {
    height: 46px;
    display: flex;
    align-items: center;

    div:first-child {
      border-right: 1px solid #ebeef5;
    }
  }

  .table-property {
    box-sizing: border-box;
    padding: 10px;
    height: 100%;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .table-content-item {
    box-sizing: border-box;
    padding: 10px;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .project-vector-content {
    .table-inline-item:first-child {
      margin-left: 15px;
      border-bottom: 1px solid #ebeef5;
    }

    .table-inline-item:last-child {
      .el-button {
        height: 32px;
        display: flex;
        padding-top: 0;
        padding-bottom: 0;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
